package com.powergisol.gis.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.powergisol.gis.dao.SzCoordsMapper;
import com.powergisol.gis.dao.TabMouldMapper;
import com.powergisol.gis.entity.SzCoords;
import com.powergisol.gis.entity.TabCoordinateSystem;
import com.powergisol.gis.listener.CoodrsListener;
import com.powergisol.gis.service.SzCoordsService;
import com.powergisol.gis.util.Result;
import com.powergisol.gis.vo.CoodrsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class SzCoordsServiceImpl implements SzCoordsService {
    @Autowired
    private TabMouldMapper tabMouldMapper;
    @Autowired
    private SzCoordsMapper szCoordsMapper;
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
    @Override
    public Result uploadFile(MultipartFile file) {
        TabCoordinateSystem system = tabMouldMapper.getCoorByName("工勘自定义坐标系");
        ExcelReader excelReader = null;
        try {
            excelReader = EasyExcel.read(file.getInputStream()).build();
            List<Sheet> sheets = excelReader.getSheets();
            for (int i = 0; i < sheets.size(); i++) {
                ReadSheet readSheet = EasyExcel.readSheet(i).head(CoodrsVO.class).registerReadListener(new CoodrsListener(szCoordsMapper,system,sheets.get(i).getSheetName())).headRowNumber(1).build();
                excelReader.read(readSheet);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (excelReader != null) {
                // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
                excelReader.finish();
            }
        }


        /*try {
            EasyExcel.read(file.getInputStream(), CoodrsVO.class, new CoodrsListener(szCoordsMapper,system,fileType)).sheet().doRead();
        } catch (IOException e) {
            throw new GlobalExceptionHandler(400, e.getMessage());
        }*/
        return new Result().success("导入成功");
    }

    @Override
    public Result select() {
        List<SzCoords> szCoords = this.szCoordsMapper.selectAll();
        return new Result().success(szCoords);
    }
}
